package cn.qiyu5522.tk_ems.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.util.SaResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.result.ResponseEnum;
import com.github.lianjiatech.retrofit.spring.boot.exception.RetrofitIOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.security.auth.message.AuthException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.*;

/**
 * @ProjectName: mybatis-plus
 * @Package: com.atuguigu.common.exception
 * @ClassName: UnifiedExceptionHandler
 * @Author: [Lucky Star]
 * @Date: 2022/10/15 16:09
 * @Version: V1.0
 **/
@Slf4j
@RestControllerAdvice
public class UnifiedExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public R handlerException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error();
    }

    @ExceptionHandler(value = BadSqlGrammarException.class)
    public R handlerException(BadSqlGrammarException e) {
        log.error(e.getMessage(), e);
        return R.setResult(ResponseEnum.BAD_SQL_GRAMMAR_ERROR);
    }

    @ExceptionHandler(value = BusinessException.class)
    public R handlerException(BusinessException e) {
        log.error(e.getMessage(), e);
        return R.error().code(e.getCode()).message(e.getMessage());
    }

    // 全局异常拦截（拦截项目中的NotLoginException异常）
    @ExceptionHandler(NotLoginException.class)
    public SaResult handlerNotLoginException(NotLoginException nle)
            throws Exception {
        // 打印堆栈，以供调试
        nle.printStackTrace();
        // 判断场景值，定制化异常信息
        String message = "";
        SaResult saResult = new SaResult();
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            saResult.setCode(50008);
            saResult.setMsg("未提供token");
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            saResult.setCode(50008);
            saResult.setMsg("token无效");
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            saResult.setCode(50014);
            saResult.setMsg("token已过期");
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            saResult.setCode(50012);
            saResult.setMsg("token已被顶下线");
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            saResult.setCode(50012);
            saResult.setMsg("token已被踢下线");
        } else {
            saResult.setCode(50015);
            saResult.setMsg("当前会话未登录");
        }
        // 返回给前端
        return saResult;
    }


    // 权限校验
    @ExceptionHandler(
            NotRoleException.class
    )
    public R handleAuthException(NotRoleException e) {
        log.error(e.getMessage(), e);
        return R.setResult(ResponseEnum.INSUFFICIENT_PERMISSIONS);
    }

    @ExceptionHandler(
            NotPermissionException.class
    )
    public R handleAuthException(NotPermissionException e) {
        log.error(e.getMessage(), e);
        return R.setResult(ResponseEnum.INSUFFICIENT_PERMISSIONS);
    }

//    // 捕获方法参数校验异常
//    @ExceptionHandler(ConstraintViolationException.class)
//    @ResponseBody
//    public ResponseEntity constraintViolationExceptionHandler(ConstraintViolationException e) {
//        Set<ConstraintViolation<?>> message = e.getConstraintViolations();
//        HashMap<String, Object> map = new HashMap<>();
//        message.stream().forEach(msg -> {
//            String path = msg.getPropertyPath().toString();
//            String field = path.substring(path.indexOf(".") + 1);
//            map.put(field, msg.getMessageTemplate());
//        });
//        return ResponseEntity.ok(map);
//    }

    @ExceptionHandler(RetrofitIOException.class)
    public R handleRetrofitIOException(RetrofitIOException e) {
        log.error(e.getMessage(), e);
        return R.setResult(ResponseEnum.REMOVE_CONNECT_ERROR);
    }


    /**
     * @param e 异常类
     * @return 响应
     * @Validated @Valid 前端提交的方式为json格式有效
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> msgList = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            msgList.add(allError.getDefaultMessage());
        }
        return R.error().message(msgList.toString());
    }


    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
     *
     * @param ex
     * @return
     * @NotBlank @NotNull @NotEmpty
     */
    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public R ConstraintViolationExceptionHandler(ConstraintViolationException ex) {

        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return  R.error().message(msgList.toString());
    }


    /**
     * Controller上一层相关异常
     */
    @ExceptionHandler({
            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    public R handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        //SERVLET_ERROR(-102, "servlet请求异常"),
        return R.error().message(ResponseEnum.SERVLET_ERROR.getMessage()).code(ResponseEnum.SERVLET_ERROR.getCode());
    }
}
